<template>
  <Dialog v-model="visible" :title="title">
    <el-form ref="formRef" v-loading="loading" :model="form" :rules="formRules" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="姓 名" prop="name">
            <el-input v-model="form.name" placeholder="请输入姓 名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="归属部门" prop="deptId">
            <el-tree-select
              v-model="form.deptId"
              :data="deptList"
              :props="defaultProps"
              check-strictly
              node-key="id"
              placeholder="请选择归属部门"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="form.mobile" maxlength="11" placeholder="请输入手机号码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮 箱" prop="email">
            <el-input v-model="form.email" maxlength="50" placeholder="请输入邮箱" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="form.username" placeholder="请输入用户名称" :disabled="!!form.id" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item v-if="!form.id" label="用户密码" prop="password">
            <el-input
              v-model="form.password"
              placeholder="请输入用户密码"
              show-password
              type="password"
              :disabled="!!form.id"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="岗 位">
            <el-select v-model="form.postIds" multiple placeholder="请选择">
              <el-option
                v-for="item in postList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备 注">
            <el-input v-model="form.remark" placeholder="请输入内容" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="loading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="visible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" name="SystemUserForm" setup>
import { defaultProps, handleTree } from '@/utils/tree'
import * as PostApi from '@/api/userCenter/dept/post'
import * as DeptApi from '@/api/userCenter/dept/dept'
import * as Api from '@/api/userCenter/dept/staff'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const visible = ref(false) // 弹窗的是否展示
const title = ref(`编辑信息`) // 弹窗的标题
const loading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const form = ref({
  name: '',
  deptId: '',
  mobile: '',
  email: '',
  id: '',
  username: '',
  password: '',
  gender: undefined,
  postIds: [],
  remark: '',
  roleIds: []
})
const formRules = reactive({
  username: [{ required: true, message: '用户名称不能为空', trigger: 'blur' }],
  name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
  password: [{ required: true, message: '用户密码不能为空', trigger: 'blur' }],
  email: [
    {
      type: 'email',
      message: '请输入正确的邮箱地址',
      trigger: ['blur', 'change']
    }
  ],
  mobile: [
    {
      pattern: /^(?:(?:\+|00)86)?1(?:3[\d]|4[5-79]|5[0-35-9]|6[5-7]|7[0-8]|8[\d]|9[189])\d{8}$/,
      message: '请输入正确的手机号码',
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref
const deptList = ref<Tree[]>([]) // 树形结构
const postList = ref<any[]>([]) // 岗位列表

/** 打开弹窗 */
const open = async (id?: string) => {
  visible.value = true

  resetForm()
  // 修改时,设置数据
  if (id) {
    loading.value = true
    form.value.id = id
    try {
      let data = await Api.getById(id)
      if (data) {
        form.value = data
      }
    } catch (t) {
      console.log(t)
    } finally {
      loading.value = false
    }
  }
  // 加载部门树
  deptList.value = handleTree(await DeptApi.getList())
  // 加载岗位列表
  postList.value = await PostApi.getList()
}
defineExpose({ open }) // 提供 open 方法,用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件,用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  loading.value = true
  try {
    const data = form.value as unknown as Api.Model
    await Api.update(data)
    message.success(`操作成功`)
    visible.value = false
    // 发送操作成功的事件
    emit('success')
  } catch (t) {
    console.log(t)
    loading.value = false
    message.error('提交表单失败')
  } finally {
    loading.value = false
  }
}

/** 重 置表单 */
const resetForm = () => {
  form.value = {
    name: '',
    deptId: '',
    mobile: '',
    email: '',
    id: '',
    username: '',
    password: '',
    gender: undefined,
    postIds: [],
    remark: '',
    roleIds: []
  }
  formRef.value?.resetFields()
}
</script>
